package com.voja.mrvica2.remoteimage;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import com.voja.mrvica2.App;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;

public class RemoteImage extends AsyncTask<Void, Void, Void> {

	public static final int MAX_SIZE = 1024 * 1024 * 5;  // 5MB
	
	ImageView vImage;
	String source;
	URL url;
	Bitmap bm;
	OnRemoteImageLoadded onComplete;
	
	RemoteImage(ImageView view, String source, OnRemoteImageLoadded onComplete) throws MalformedURLException {
		this.source = source;
		url = new URL(source);
		vImage = view;
		this.onComplete = onComplete;
	}
	
	@Override
	protected Void doInBackground(Void... arg0) {
			
		try {
			bm = App.cache.getBitmap(source);
			if (bm == null) {
				HttpURLConnection conn;
				conn = (HttpURLConnection)url.openConnection();
				conn.setDoInput(true);
				conn.connect();
				InputStream in = conn.getInputStream();
				bm = BitmapFactory.decodeStream(in);	
				App.cache.setBitmap(source, bm);
			}
			bm = App.cache.getBitmap(source);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	@Override
	protected void onPostExecute(Void result) {
		try {
		    vImage.setImageBitmap(bm);
			if (onComplete != null) {
			    onComplete.bitmap = bm;
				onComplete.call();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
